package com.file.choose.montaro;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StrictMode;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.HashMap;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;

public class FileChoose extends AppCompatActivity{
    public String CurrentPath;
    ListView lv=null;
    TextView TV=null;
    SimpleAdapter sAdpater;
    String tmpPath;
    File tmpFile=null;
    ImageButton IB=null;
    String moveDir="";
    ArrayList<FileClass> CurrentFiles=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.choose_file);
        if(Build.VERSION.SDK_INT>=18) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
            builder.detectFileUriExposure();
        }
        //Log.i("SDcard Path",Environment.getExternalStorageDirectory().getPath());
        IB=(ImageButton)findViewById(R.id.UseCamera);
        IB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openCamera(view);
            }
        });
        CurrentPath=getData("CurrentPath");
        if(CurrentPath.equals("")) {
            setData("CurrentPath", Environment.getExternalStorageDirectory().getPath() + "/");
            CurrentPath=getData("CurrentPath");
        }
        CurrentFiles=ListFiles(CurrentPath);
        CurrentFiles= new FileClass().Order(CurrentFiles);
        ShowFileInListView(CurrentFiles);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                TV=(TextView)view.findViewById(R.id.Item_Text);
                if(i==0&&TV.getText().equals("...")){
                    //到上一级
                    if(CurrentPath.length()==0)
                        return ;
                    int last=CurrentPath.lastIndexOf("/",CurrentPath.length()-2);
                    //Log.i("Last",last+"");
                    CurrentPath = CurrentPath.substring(0, last==-1?CurrentPath.length():last+1);
                }
                tmpPath=CurrentPath+TV.getText();
                Log.i("tmpPath",tmpPath);
                tmpFile=new File(tmpPath);
                if(tmpFile.isFile()){
                    AlertDialog.Builder AB=new AlertDialog.Builder(FileChoose.this);
                    AB.setTitle("选择这个文件吗?");
                    AB.setMessage(tmpPath);
                    AB.setCancelable(false);
                    AB.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Intent Myself=getIntent();
                            Uri outputPath;
                            outputPath=Myself.getParcelableExtra("output");
                            if(outputPath!=null) {
                                if (CopySdcardFile(tmpPath, outputPath.getPath())) {
                                    Intent result=new Intent();
                                    if(getData("option").equals("move")){
                                        moveDir=getData("moveDir");
                                        if(moveDir.equals("")){
                                            moveDir=Environment.getExternalStorageDirectory().getPath();
                                            moveDir+="/backupFile/";//默认路径
                                            new File(moveDir).mkdirs();
                                        }
                                        if(tmpFile.renameTo(new File(moveDir+TV.getText()))){
                                            Log.i(
                                                    "* * Move File",
                                                    "Move to "+moveDir+" Success!"
                                            );
                                        }else
                                        {
                                            Log.i(
                                                    "* * Move File",
                                                    "Move to "+moveDir+" Failed!"
                                            );
                                        }
                                    }
                                    if(getData("option").equals("dele")){
                                        tmpFile.delete();
                                    }
                                    setResult(RESULT_OK,result);//返回数据
                                    finish();
                                }
                            }
                        }
                    });
                    AB.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i){

                        }
                    });
                    AB.show();
                }else{//进入下一级目录
                    if(!(i==0&&TV.getText().equals("..."))){
                        CurrentPath=tmpPath+"/";
                    }
                }
                Log.i("CurrentPath",CurrentPath);
                CurrentFiles=ListFiles(CurrentPath);
                CurrentFiles=new FileClass().Order(CurrentFiles);
                ShowFileInListView(CurrentFiles);
            }
        });

        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int which, long id) {
                //弹出询问是否删除对话框 并返回true
                return false;
            }
        });
    }
    public String getFileSize(String filename){
        String Size="";
        String dw="B";
        File f=new File(filename);
        double B=f.length();
        if(B>1024)
        {
            B/=1024;
            dw="K";
        }
        if(B>1024)
        {
            B/=1024;
            dw="M";
        }
        if(B>1024)
        {
            B/=1024;
            dw="G";
        }
        if(B>1024)
        {
            B/=1024;
            dw="T";
        }
        DecimalFormat df = new DecimalFormat("0.00");
        Size=df.format(B)+dw;
        return Size;
    }
    public ArrayList<FileClass> ListFiles(String path){
        if(path.length()<=0)
            return null;
        if(!new File(path).exists()){
            Toast.makeText(this,"设定目录不存在，已切换至存储卡。",Toast.LENGTH_SHORT).show();
            path=Environment.getExternalStorageDirectory()+"/";
        }
        if(!path.substring(path.length()-1,path.length()).equals("/"))
            path+="/";
        //Log.i("Path",path);
        ArrayList<FileClass> files=new ArrayList<>();
        String state = Environment.getExternalStorageState();
        if (!Environment.MEDIA_MOUNTED.equals(state)) {
            //Log.i("Sdcard","Mounted!");
            return null;
        }
        File AllFile=new File(path);
        if(AllFile==null)
        {
            //Log.i("AllFile","AllFile is null!");
            return null;
        }
        String[] FileArray=AllFile.list();
        if(!CurrentPath.equals(Environment.getExternalStorageDirectory()+"/")) {
            FileClass FS = new FileClass();
            FS.path = "...";
            FS.isFile = 0;
            files.add(FS);
        }
        for(String single:FileArray)
        {
            FileClass fileclass=new FileClass();
            //Log.i("ListFiles",single);
            fileclass.path=single;
            fileclass.isFile=(new File(path+single)).isFile()?1:2;
            //Log.i(new File())
            files.add(fileclass);
        }
        return files;
    }
    public static boolean CopySdcardFile(String fromFile, String toFile) {

        try {
            InputStream fosfrom = new FileInputStream(fromFile);
            OutputStream fosto = new FileOutputStream(toFile,true);
            byte bt[] = new byte[1024];
            int c;
            while ((c = fosfrom.read(bt)) > 0) {
                fosto.write(bt, 0, c);
            }
            fosto.write(0);//追加一个0以达到修改文件哈希值的目的
            fosfrom.close();
            fosto.close();
            return true;

        } catch (Exception ex) {
            return false;
        }
    }
    public void openCamera(View v) {
        Intent I=new Intent("android.media.action.IMAGE_CAPTURE");
        I.putExtra("output", getIntent().getParcelableExtra("output"));
        I.setComponent(new ComponentName("com.huawei.camera","com.huawei.camera.controller.ThirdCameraActivity"));
        startActivityForResult(I,222);
    }
    @Override
    public void onActivityResult(int requestCode,int resultCode,Intent data){
        setResult(resultCode,data);
        super.onActivityResult(requestCode,resultCode,data);
        finish();
    }
    public void ShowFileInListView(ArrayList<FileClass> FS){
        if(FS==null)
            return;
        FS=new FileClass().Order(FS);
        String[] Data=new FileClass().FileClassToString(FS);
        ArrayAdapter<String> adpater=new ArrayAdapter<String>(FileChoose.this,android.R.layout.simple_list_item_1,Data);
        ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String,Object>>();
        HashMap<String, Object> map = new HashMap<String, Object>();
        /*if(!CurrentPath.equals(Environment.getExternalStorageDirectory().getPath()+"/"))
        {
            map = new HashMap<String, Object>();
            map.put("Image",R.drawable.back);
            map.put("Title","...");
            listItem.add(map);
        }*/
       /* map = new HashMap<String, Object>();
        map.put("Image",R.drawable.camera);
        map.put("Title","使用相机拍照");
        listItem.add(map);
        */
        for(FileClass sFS:FS)
        {
           map = new HashMap<String, Object>();
            int image;
            if(sFS.isFile==1)
                image=R.drawable.file;
            else if(sFS.isFile==2)
                image=R.drawable.folder;
            else
                image=R.drawable.back;
            map.put("Image",image);
            map.put("Title",sFS.path);
            if(sFS.isFile==1)
            {
                map.put("Size",getFileSize(CurrentPath+sFS.path));
            }
            listItem.add(map);
        }
        sAdpater = new SimpleAdapter(
                this,
                listItem,
                R.layout.listview_item,
                new String[]{"Image", "Title","Size"},
                new int[]{R.id.Item_Image, R.id.Item_Text,R.id.Item_Size});
        lv=(ListView)findViewById(R.id.ListView_File_Chooser);
        lv.setAdapter(sAdpater);
    }
    public String getData(String Key){
        SharedPreferences sp=this.getSharedPreferences("Data", MODE_PRIVATE);
        return sp.getString(Key,"");
    }
    public void setData(String Key,String Data){
        SharedPreferences sp=this.getSharedPreferences("Data", MODE_PRIVATE);
        SharedPreferences.Editor ed=sp.edit();
        ed.putString(Key,Data);
        ed.apply();
    }
    @Nullable
    public static String getFileMD5(File file) {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[1024];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        BigInteger bigInt = new BigInteger(1, digest.digest());
        return bigInt.toString(16);
    }
}
class FileClass{
    public String path;
    public int isFile;//File 1 Dir 2
    public FileClass(){
        path="";
        isFile=0;
    }
    public String[] FileClassToString(ArrayList<FileClass> FS){
        String [] str=new String[FS.size()];
        int i=0;
        for(FileClass s:FS)
        {
            str[i]=s.path;
            //Log.i("str",str[i]);
            i++;
        }
        return str;
    }
    public String getName(@Nullable String str){
        if(str==null)
            str="/";
        String name=path.substring(path.lastIndexOf(str),path.length());
        Log.i("getName",name);
        return name;
    }
    public ArrayList<FileClass> Order(ArrayList<FileClass> FS) {
        ArrayList<FileClass> newFS=new ArrayList<>();
        String[] F=FileClassToString(FS);
        Arrays.sort(F);
        int i=0;
        for(FileClass t:FS)
        {
            FileClass a=new FileClass();
            a=Search(FS,F[i]);
            newFS.add(a);
            i++;
        }
        return newFS;
    }
    public FileClass Search(ArrayList<FileClass> FS,String path){
        for(FileClass fs:FS)
        {
            if(fs.path.equals(path))
                return fs;
        }
        return null;
    }

}
